// packageA/pages/create_coupon/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isEdit: false,
        editId: null,
        isFormValid: false,
        formData: {
            name: '满减券',
            type: 'full_reduce',
            fullAmount: '10',
            reduceAmount: '7',
            discount: '10',
            startTime: '',
            endTime: '',
            description: ''
        },
        couponTypes: [
            { label: '满减券', value: 'full_reduce' },
            { label: '直减券', value: 'direct_reduce' },
            { label: '折扣券', value: 'discount' },
            { label: '免邮券', value: 'Free_shipping' }
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.id) {
            this.setData({
                isEdit: true,
                editId: options.id
            });
            this.loadEditData(options.id);
        }
        this.validateForm();
    },
    // 加载编辑数据
    loadEditData(id) {
        // 模拟从数据库加载数据
        const editData = {
            name: '满100减20',
            type: 'full_reduce',
            fullAmount: '100',
            reduceAmount: '20',
            startTime: '2025-11-01',
            endTime: '2025-11-30',
            description: '满100元减20元，适用于全平台商品'
        };

        this.setData({
            'formData': editData
        });
    },

    // 类型选择
    onTypeChange(e) {
        const type = e.currentTarget.dataset.type;
        console.log(type);
        let name = '满减券';
        switch (type) {
            case 'full_reduce':
                name = '满减券';
                break;
            case 'direct_reduce':
                name = '直减券';
                break;
            case 'discount':
                name = '折扣券';
                break;
            case 'Free_shipping':
                name = '折扣券';
                break;
            default:

                break;
        }
        this.setData({
            'formData.type': type,
            'formData.name':name,
            'formData.fullAmount': '',
            'formData.reduceAmount': '',
            'formData.discount': '',
            'formData.Free_shipping': ''
        });
        this.validateForm();
    },

    // 表单输入
    onFormInput(e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail.value;
        this.setData({
            [`formData.${field}`]: value
        });
        this.validateForm();
    },

    // 开始时间选择
    onStartTimeChange(e) {
        this.setData({
            'formData.startTime': e.detail.value
        });
        this.validateForm();
    },

    // 结束时间选择
    onEndTimeChange(e) {
        this.setData({
            'formData.endTime': e.detail.value
        });
        this.validateForm();
    },

    // 表单验证
    validateForm() {
        const { name, type, startTime, endTime } = this.data.formData;

        let isValid = name.trim() && startTime && endTime;
        // 根据类型验证必填字段
        if (type === 'full_reduce') {
            isValid = isValid && this.data.formData.fullAmount && this.data.formData.reduceAmount;
        } else if (type === 'direct_reduce') {
            isValid = isValid && this.data.formData.reduceAmount;
        } else if (type === 'discount') {
            isValid = isValid && this.data.formData.discount;
        } else if (type === 'Free_shipping') {
            isValid = true
        }

        this.setData({ isFormValid: isValid });
    },

    // 表单提交
    onSubmit(e) {
        if (!this.data.isFormValid) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            });
            return;
        }

        const formData = e.detail.value;
        const completeData = {
            ...this.data.formData,
            ...formData
        };

        this.saveCouponData(completeData);
    },

    // 保存优惠券数据
    saveCouponData(data) {
        // 模拟保存到本地存储
        const coupons = wx.getStorageSync('coupons') || [];

        if (this.data.isEdit) {
            // 编辑模式
            const index = coupons.findIndex(item => item.id === this.data.editId);
            if (index !== -1) {
                coupons[index] = {
                    ...coupons[index],
                    ...data
                };
            }
        } else {
            // 创建模式
            const newCoupon = {
                id: Date.now(),
                ...data,
                createTime: new Date().toISOString().split('T')[0],
                status: 'active'
            };
            coupons.push(newCoupon);
        }

        wx.setStorageSync('coupons', coupons);

        wx.showToast({
            title: this.data.isEdit ? '更新成功' : '创建成功',
            icon: 'success',
            success: () => {
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            }
        });
    },

    // 取消操作
    onCancel() {
        wx.navigateBack();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})